<template>
	<view class="bg-login">
		<view class="pages-up-divider">
			<up-divider
				text="欢迎使用慧治理管理平台"
				textColor="#fff"
				hairline
				textSize="28rpx"
				lineColor="#fff"
			></up-divider>
		</view>
		
		<view class="login_btn">
			<button 
				open-type="getPhoneNumber" 
				@getphonenumber="onGetPhoneNumber"
			>
				<image src="../../static/icon/wx.svg" mode="" class="icon-font"></image>
				微信一键登录
			</button>
		</view>
	</view>
</template>

<script setup>
	import { onGetWxOpenid, onGetWxPhoneNumber } from "/serves/api.js"
	import { reactive, ref } from "vue";
	import { onLoad } from "@dcloudio/uni-app";
	import { setAuthorization } from "/common/constant.js"
	
	const count = ref(0)
	const loginInfo = ref({
		openpid: null,
		phone: null,
	})


	const onGetPhoneNumber = async (e) => {
		if (e.detail.errMsg != "getPhoneNumber:ok") {
			uni.showToast({ title: '请重新点击授权', icon: 'none' })
			return;
		}
		
		const { code } = e.detail
		const params = { openId: loginInfo.value.openpid, phoneCode: code  }
		
		const response = await onGetWxPhoneNumber(params)
		const { access_token } = response.data
		setAuthorization(access_token)
		wx.reLaunch({ url: '/pages/index/index' })
	};
	
	const wxLogin = function () {
		uni.login({
			provider: 'weixin',
			success: async function(resolve) {
				const { code } = resolve
				const response = await onGetWxOpenid({ code })
				loginInfo.value.openpid = response.data
			},
			fail: function(err) {
				count.value += 1
				if (count.value > 5) {
					uni.showToast({
						title: '服务异常，请重新进入小程序重试！',
						icon: 'none'
					})
					return 
				}
				
				wxLogin()
			}
		});
	}
	
	onLoad(() => wxLogin())
</script>

<style scoped lang="scss">
	.bg-login {
		box-sizing: border-box;
		padding: 200rpx 115rpx 600rpx; 
		background-repeat: no-repeat;
		background-size: 100% 100%;
		background-image: url(http://101.33.235.253:9300/statics/2024/09/09/bg_20240909211214A007.jpeg);
		width: 100%;
		height: 100vh;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-direction: column;
	}

	.pages-up-divider {
		display: block;
		width: 100%;
		margin-bottom: 100rpx;
	}

	.login_btn {
		width: 100%;
		padding: 28rpx 110rpx;
		
		button {
			width: 100%;
			height: 100rpx;
			font-size: 34rpx;
			background: #44A4FF;
			color: #fff;
			border-radius: 4rpx;
			display: flex;
			font-weight: 500;
			align-items: center;
			justify-content: center;
			box-shadow: 0px 0px 10rpx 0px rgba(109,114,141,0.08), 0px 2rpx 6rpx 0px rgba(0,0,0,0.1);
			
			&:active {
				background: #2E90EC;
				box-shadow: 0px 0px 10rpx 0px #1B7BFA, 0px 2rpx 6rpx 0px #1B7BFA;
			}

			&::after {
				border: none;
				border-radius: 0;
			}
		}
		
		.icon-font {
			width: 50rpx;
			height: 50rpx;
			margin-right: 20rpx;
		}
	}
</style>